package com.cake.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cake.dao.XxAdminRoleMapper;
import com.cake.dao.XxMenuMapper;
import com.cake.dao.XxRoleMapper;
import com.cake.dao.XxRoleMenuMapper;
import com.cake.entity.XxAdminRoleKey;
import com.cake.entity.XxMenu;
import com.cake.entity.XxRole;
import com.cake.entity.XxRoleMenuKey;
import com.cake.service.base.BaseService;
import com.cake.service.inter.IXxRoleService;

/**
 * 角色业务层
 * @author Administrator
 *
 */
@Service
@Transactional
public class XxRoleServiceImpl extends BaseService<XxRole> implements IXxRoleService{

	@Autowired
	private XxRoleMapper xxRoleMapper;
	
	@Autowired
	private XxAdminRoleMapper xxAdminRoleMapper;
	
	@Autowired
	private XxMenuMapper xxMenuMapper;
	
	@Autowired
	private XxRoleMenuMapper xxRoleMenuMapper;
	
	@Override
	public List<XxRole> selectAllRoles() {
		return xxRoleMapper.selectAllRoles();
	}

	@Override
	public Integer updateAdminRoles(String[] roles, Long adminId) {
		Integer deleteCode = xxAdminRoleMapper.delectAdminRolesByAdminId(adminId);
		Integer updateCode = 0;
		if(deleteCode >= 0){
			XxAdminRoleKey xxAdminRoleKey = new XxAdminRoleKey();
			for (int i = 0; i < roles.length; i++) {
				xxAdminRoleKey.setAdmins(adminId);
				xxAdminRoleKey.setRoles(Long.parseLong(roles[i]));
				updateCode = updateCode + xxAdminRoleMapper.insert(xxAdminRoleKey);
			}
		}
		return updateCode;
	}

	@Override
	public XxRole selectRoleAndMenuByRoleId(Long roleId) {
		XxRole xxRole = xxRoleMapper.selectByPrimaryKey(roleId);
		List<XxMenu> list = xxMenuMapper.selectMenusByRoleId(roleId);
		String menuIds = "";
		for (int i = 0; i < list.size(); i++) {
			if(i == list.size() - 1){
				menuIds = menuIds + list.get(i).getId();
			}else{
				menuIds = menuIds + list.get(i).getId() + ",";
			}
		}
		xxRole.setMenuIds(menuIds);
		return xxRole;
	}

	@Override
	public Integer insertOrUpdateRole(XxRole xxRole) {
		Integer saveCode = 0;
		if(xxRole.getId() == null){
			xxRole.setCreateDate(new Date());
			xxRole.setIsSystem(false);
			saveCode = xxRoleMapper.insert(xxRole);
		}else{
			saveCode = xxRoleMapper.updateByPrimaryKeySelective(xxRole);
			xxRoleMenuMapper.deleteMenuByRoleId(xxRole.getId());
		}
		String menuIdsStr = xxRole.getMenuIds();
		if(menuIdsStr.length() > 0){
			String[] menuIds = menuIdsStr.split(",");
			for (int i = 0; i < menuIds.length; i++) {
				XxRoleMenuKey xxRoleMenuKey = new XxRoleMenuKey();
				xxRoleMenuKey.setMenus(Long.parseLong(menuIds[i]));
				xxRoleMenuKey.setRoles(xxRole.getId());
				xxRoleMenuMapper.insert(xxRoleMenuKey);
			}
		}
		return saveCode;
	}

}
